package com.itheima.controller;


import com.itheima.common.R;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.path}")
    private String path;


    //加注解只是为了优雅
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws IOException {
        InputStream fileInputStream = file.getInputStream();
        String filename = file.getOriginalFilename();
        //String filename ="1200.jpg";
        UUID uuid = UUID.randomUUID();
        String name = uuid + filename.substring(filename.lastIndexOf("."));
       // System.out.println(name);
        File dir = new File(path,name);
        //file.transferTo(dir);
        if (dir.exists()) {
            file.transferTo(dir);
        } else {
            dir.mkdirs();
            file.transferTo(dir);
        }
        //System.out.println(name);
        return R.success(name);
    }


    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        try {
            response.setContentType("image/jpeg");
            FileInputStream fileInputStream =
                    new FileInputStream(new File(path,name));
            ServletOutputStream outputStream = response.getOutputStream();
            IOUtils.copy(fileInputStream,outputStream);
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
